/**
 *
 */
package com.csun.cmny.provider.service.impl;

import com.csun.cmny.core.support.BaseService;
import com.csun.cmny.provider.dao.BedMapper;
import com.csun.cmny.provider.dao.GroupMapper;
import com.csun.cmny.provider.dao.SessionMapper;
import com.csun.cmny.provider.dto.Group;
import com.csun.cmny.provider.dto.NursingBindRoomDto;
import com.csun.cmny.provider.model.dto.user.OmcUserQueryDto;
import com.csun.cmny.provider.model.enums.UacGroupTypeEnum;
import com.csun.cmny.provider.model.vo.CountVo;
import com.csun.cmny.provider.model.vo.GroupVo;
import com.csun.cmny.provider.model.vo.OmcUserVo;
import com.csun.cmny.provider.pojo.Bed;
import com.csun.cmny.provider.pojo.NursingGroup;
import com.csun.cmny.provider.pojo.Room;
import com.csun.cmny.provider.pojo.User;
import com.csun.cmny.provider.resolver.CmnyMessageSource;
import com.csun.cmny.provider.service.OmcGroupService;
import com.csun.cmny.provider.service.UacRpcService;
import com.csun.cmny.provider.vo.*;
import com.csun.cmny.util.PublicUtil;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.temporal.WeekFields;
import java.util.*;

/**
 * @author chenzheng
 * @date 2019年7月16日
 * @time 上午9:53:42
 * Description :
 */
@Transactional
@Service("OmcGroupService")
public class OmcGroupServiceImpl extends BaseService<NursingGroup> implements OmcGroupService {

    @Resource
    private CmnyMessageSource cmnyMessageSource;
    @Resource
    private SessionMapper sessionMapper;

    @Resource
    private GroupMapper groupMapper;

    @Resource
    private BedMapper bedMapper;

    @Resource
    private UacRpcService uacRpcService;


    /*
     * 删除护工组
     */
    @Override
    public int deleteById(Long nursingGroupId) {
        String msg_gsi_group_id_not_exist = cmnyMessageSource.getMessage("gsi.group.id.not.exist", null);

        int n = groupMapper.deleteByPrimaryKey(nursingGroupId);
        if (n <= 0) {
            throw new RuntimeException(msg_gsi_group_id_not_exist);
        } else {
            //删除班组绑定的护工和房间
            groupMapper.deleteRoomBindById(nursingGroupId);
            groupMapper.deleteUserBindById(nursingGroupId);
        }
        return n;
    }


    /*
     * 添加护工组
     */
    @Override
    public int insert(Group group) {
		
	/*	Locale locale = LocaleContextHolder.getLocale();
		String msg_comment_insert_fail = messageSource.getMessage("comment.insert.fail", new Object[]{}, locale);*/

        int n = groupMapper.insertSelectiveByGroup(group);
		/*if(n <= 0){
			throw new RuntimeException(msg_comment_insert_fail);
		}*/
        return n;
    }

    @Override
    public int insertNursingGroupBind(List<User> list) {
        return groupMapper.insertNursingGroupBind(list);
    }


    /*
     * 修改护工组信息
     */
    @Override
    public int updateById(Group group) {

        return groupMapper.updateByIdSelective(group);
    }

    /**
     * 根据班组Id修改该班组班长
     *
     * @param group the group
     *
     * @return  the int.
     */
    @Override
    public int updateUserIdByGroupId(Group group) {

        /**
         * @data 2019-09-04
         * @author chisj
         * @desc 更换班长后，清除用户token
         */
        NursingGroup nursingGroup = groupMapper.selectByPrimaryKey(group.getNursingGroupId());

        int n = groupMapper.updateByIdSelective(group);

        if (n > 0
                && PublicUtil.isNotEmpty(nursingGroup)
                && PublicUtil.isNotEmpty(nursingGroup.getUserId())) {

            // 清除
            uacRpcService.restToken(group.getUserId());

            // 根据userId清除Token
            uacRpcService.restToken(nursingGroup.getUserId());
        }

        return n;
    }
    /*
     * 大数据平台健康占比亚健康展示
     * */
    @Override
    public NurseHomeVo selectByNursingHome(Long groupId) {

        /**
         * @date    2021-11-19
         * @author  chisj
         * @desc    获取子机构id集合
         */
        List<GroupVo> groupVoList = uacRpcService.queryGroupListByGroupId(groupId);
        if (PublicUtil.isEmpty(groupVoList)) {
            return null;
        }

        List<Long> groupIdList = Lists.newArrayList();
        for (GroupVo gv : groupVoList) {
            groupIdList.add(gv.getId());
        }

        //查询该品台下机构类别
        //List<CountVo> countVos = groupMapper.selectType(groupIdList);
        List<com.csun.cmny.provider.model.vo.CountVo> countVos = uacRpcService.selectType(groupId);

        Map<String,String> nursingMap = new HashMap<String,String>();
        for (CountVo countVo:countVos) {
            nursingMap.put(countVo.getNum(),countVo.getType());
        }
        for (String key:nursingMap.keySet()) {
            String nursingType = UacGroupTypeEnum.getValue(nursingMap.get(key));
            nursingMap.put(key,nursingType);
        }

        //查询已评价老人自理程度占比
        NurseHomeVo nurseHomeVo = groupMapper.selectByNursingHome(groupIdList);
        nurseHomeVo.setNurseHomeType(nursingMap);
        List<PercentVo> percentVos = new ArrayList<>();
        DecimalFormat df = new DecimalFormat("0.00%");
        PercentVo percentVo = new PercentVo();
        percentVo = new PercentVo("失能失智",nurseHomeVo.getIncapacitation(),
                df.format(nurseHomeVo.getIncapacitation().doubleValue()/nurseHomeVo.getCount()));
        percentVos.add(percentVo);
        percentVo = new PercentVo("半失能",nurseHomeVo.getHalfIncapacitation(),
                df.format(nurseHomeVo.getHalfIncapacitation().doubleValue()/nurseHomeVo.getCount()));
        percentVos.add(percentVo);
        percentVo = new PercentVo("自理",nurseHomeVo.getHealth(),
                df.format(nurseHomeVo.getHealth().doubleValue()/nurseHomeVo.getCount()));
        percentVos.add(percentVo);
        nurseHomeVo.setPercentVos(percentVos);
        return nurseHomeVo;
    }
    /**
     * 护工绑定房间
     */
    @Override
    public Integer nursingBindRoom(NursingBindRoomDto nursingBindRoomDto) {
        return groupMapper.nursingBindRoom(nursingBindRoomDto);
    }

    @Override
    public void deleteByUserId(List<Long> userIds) {
        groupMapper.deleteByUserId(userIds);
    }
    //护工绑定护工组
    @Override
    public void nursingBindNursingGroup(NursingBindRoomDto nursingBindRoomDto) {
        groupMapper.nursingBindNursingGroup(nursingBindRoomDto);
    }

    @Override
    public void deleteByNursingGroupId(NursingBindRoomDto nursingBindRoomDto) {
        groupMapper.deleteByNursingGroupId(nursingBindRoomDto);
    }


    /*
     * 通过名称和机构id判断该名称是否已经存在
     */
    @Override
    public int selectByName(Group group) {
        List<NursingGroupVo> list = groupMapper.selectByName(group);
        return list.size();
    }


    @Override
    public List<NursingGroupVo> selectListByName(Group group) {
        return groupMapper.selectListByName(group);
    }

    /*
     * 根据buildingId查询没有被分配的房间
     */
    @Override
    public List<Room> selectByBuildingId(Long buildingId) {
        return groupMapper.selectByBuildingId(buildingId);
    }

    @Override
    public List<OmcUserVo> selectByGroupId(Long groupId) {
        Group group = new Group();
        group.setNursingGroupId(groupId);
        List<NursingGroupVo> nursingGroupList = groupMapper.selectByName(group);//查询护工组信息
        List<Long> userIdList = groupMapper.selectUserIdListById(groupId);//获取护工组绑定的护工I

        List<OmcUserVo> list = new ArrayList<>();
        if (null != userIdList && userIdList.size() > 0) {
            OmcUserQueryDto omcUserQueryDto = new OmcUserQueryDto();
            omcUserQueryDto.setRoleCode("nursing");//护工角色code
            omcUserQueryDto.setUserIdList(userIdList);
            list = uacRpcService.queryOmcUserListByQueryDto(omcUserQueryDto);
        }
        if (nursingGroupList.size() > 0) {
            for (OmcUserVo omcUserVo : list) {
                omcUserVo.setNursingGroupName(nursingGroupList.get(0).getName());//填充护工组名称
                omcUserVo.setNursingGroupId(nursingGroupList.get(0).getId());//填充护工组ID
            }
        }
        return list;
    }

    @Override
    public List<OmcUserVo> selectUnUnrsingUserListByGroupId(Group group) {
        List<Long> list = new ArrayList<>();

        //查询改机构下班组已有的护工
        List<NursingGroupVo> nursingGroupList = groupMapper.selectNursingListByName(group);
        if (null != nursingGroupList && nursingGroupList.size() > 0) {
            for (NursingGroupVo nursingGroup : nursingGroupList
                    ) {
                if (nursingGroup.getNursingUserId() != null && nursingGroup.getNursingUserId() > 0) {
                    list.add(nursingGroup.getNursingUserId());
                }
            }
        }
        //去重
        LinkedHashSet<Long> set = new LinkedHashSet<Long>(list.size());
        set.addAll(list);
        list.clear();
        list.addAll(set);
        return uacRpcService.queryOmcUnUnrsingUserListByUserIds(list, group.getGroupId(), "nursing");
    }


    @Override
    public List<NursingGroupBind> selectNursingGroupBind(Group group) {
        return groupMapper.selectNursingGroupBind(group);
    }

    @Override
    public List<NursingGroupVo> selectShowAll(Group group) {
        List<NursingGroupVo> list = groupMapper.selectListByName(group);

        /**
         * @date    2020-08-11
         * @author  chisj
         * @desc    新增班组是否有待审批排班计划
         */
        List<Long> nursingGroupIds = Lists.newArrayList();

        List<Long> userList = new ArrayList<>();
        if (null != list && list.size() > 0) {
            for (NursingGroupVo nursingGroup : list) {
                userList.add(Long.valueOf(nursingGroup.getUserId()));
                nursingGroupIds.add(nursingGroup.getId());
            }
        }
        List<OmcUserVo> omcUserVos = new ArrayList<>();
        if (userList.size() > 0) {
            omcUserVos = uacRpcService.queryOmcUserListByUserIds(userList);
        }

        Map<String, Object> params = new HashMap<>();
        // 获取年
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        // 获取周次
        WeekFields weekFields = WeekFields.of(Locale.getDefault());
        int week = LocalDate.now().get(weekFields.weekOfWeekBasedYear());

        Map<Integer, Long> map = new HashMap<>();
        if (PublicUtil.isNotEmpty(nursingGroupIds)) {
            params.put("nursingGroupIds", nursingGroupIds);
            params.put("year", year);
            params.put("week", week);

//            map = groupMapper.queryNursingGroupNum(params);
            map = sessionMapper.queryNursingGroupNum(params);
        }

        boolean flag = false;
        if (PublicUtil.isNotEmpty(map)) {
            flag = true;
        }

        if (null != list && list.size() > 0) {
            for (NursingGroupVo nursingGroup : list) {

                /**
                 * @date    2020-08-12
                 * @author  chisj
                 * @desc    待审批排班提示
                 */
                if (flag) {
                    if (PublicUtil.isNotEmpty(map.get(nursingGroup.getId().intValue()))) {
                        nursingGroup.setNums(map.get(nursingGroup.getId().intValue()).intValue());

                        //记录待审批状态
                        nursingGroup.setIsApply(0);
                    }
                }

                Long usrId = Long.valueOf(nursingGroup.getUserId());
                if (null != omcUserVos && omcUserVos.size() > 0) {
                    for (OmcUserVo omcUserVo :
                            omcUserVos) {
                        if (usrId.equals(omcUserVo.getUserId())) {
                            nursingGroup.setRealName(omcUserVo.getRealName());
                            break;
                        }
                    }
                }
            }
        }

        return list;
    }

    @Override
    public List<NursingGroupVo> selectNursingListByName(Group group) {
        List<NursingGroupVo> list = groupMapper.selectNursingListByName(group);
        //护工ID集合
        List<Long> userList = new ArrayList<>();
        if (null != list && list.size() > 0) {
            for (NursingGroupVo nursingGroup : list) {
                userList.add(nursingGroup.getNursingUserId());
            }
        }
        //远程查询护工信息并填充返回
        List<OmcUserVo> omcUserVos = new ArrayList<>();
        if (userList.size() > 0) {
            omcUserVos = uacRpcService.queryOmcUserListByUserIds(userList);
        }
        if (null != list && list.size() > 0) {
            for (NursingGroupVo nursingGroup : list) {
                Long userId = nursingGroup.getNursingUserId();
                if (null != omcUserVos && omcUserVos.size() > 0) {
                    for (OmcUserVo omcUserVo : omcUserVos) {
                        if (userId != null && userId.equals(omcUserVo.getUserId())) {
                            nursingGroup.setNursingRealName(omcUserVo.getRealName());
                            nursingGroup.setDepartmentId(omcUserVo.getDepartmentId());
                            nursingGroup.setNursingUserGoupId(omcUserVo.getGroupId());
                            nursingGroup.setIdentityNumber(omcUserVo.getIdentityNumber());
                            nursingGroup.setNursingUserId(omcUserVo.getUserId());
                            nursingGroup.setNursingUserName(omcUserVo.getUserName());
                            nursingGroup.setPhone(omcUserVo.getPhone());
                            nursingGroup.setSex(omcUserVo.getSex());
                            break;
                        }
                    }
                }
            }
        }
        return list;
    }

    @Override
    public int deleteNursingGroupBind(Group group) {
        if (group.getUserId() <= 0 && group.getNursingGroupId() <= 0 && group.getNursingGroupBindId() <= 0) {

            throw new RuntimeException("请传护工ID、绑定关系ID、护工组ID至少一个参数");

        } else {
            return groupMapper.deleteNursingGroupBind(group);
        }

    }

    @Override
    public int insertNursingRoomBind(List<Room> list) {
        return groupMapper.insertNursingRoomBind(list);
    }

    @Override
    public List<Room> selectForBuilding(Group group) {
        return groupMapper.selectForBuilding(group);
    }

    @Override
    public int deleteNursingRoomBind(List<Room> list, Long nursingGroupId) {
        return groupMapper.deleteNursingRoomBind(list, nursingGroupId);
    }

    @Override
    public List<Room> selectNursingBindRoom(Long nursingGroupId) {
        return groupMapper.selectNursingBindRoom(nursingGroupId);
    }

    @Override
    public List<Bed> selectByRoomId(Long roomId) {
        return bedMapper.selectByRoomId(roomId.intValue());
    }

    @Override
    public Long selectNuringGroupIdByUserId(Long userId) {
        return groupMapper.selectNuringGroupIdByUserId(userId);
    }

    /**
     * 查询userId集合中已绑定护工组的护工
     *
     * @param userList
     * @return
     */
    @Override
    public List<OmcUserVo> isNursingbind(List<Long> userList) {
        List<OmcUserVo> list = new ArrayList<>();
        List<Long> users = groupMapper.selectNusringBindByList(userList);
        if (users.size() > 0) {
            list = uacRpcService.queryOmcUserListByUserIds(users);
        }
        return list;
    }

    /**
     * 根据用户ID查询用户详情
     *
     * @param userId  用户ID
     * @param groupId 组织机构ID
     * @return
     */
    @Override
    public OmcUserDetailVo queryUserDetail(Long userId, Long groupId) {
        OmcUserDetailVo omcUserDetailVo = new OmcUserDetailVo();
        List<NursingGroupVo> nursingGroupList = new ArrayList<>();
        Long nursingGroupId = groupMapper.selectNuringGroupIdByUserId(userId);
        if (nursingGroupId > 0) {//用户绑定了护工组才去查询护工组信息
            Group group = new Group();
            group.setGroupId(groupId);
            group.setNursingGroupId(nursingGroupId);
            nursingGroupList = groupMapper.selectByName(group);//查询护工组信息
        }
//        else{
//            throw new OmcBizException(ErrorCodeEnum.OMC10035006);
//        }
        //远程查询用户信息
        OmcUserQueryDto omcUserQueryDto = new OmcUserQueryDto();
        omcUserQueryDto.setUserId(userId);
        omcUserQueryDto.setGroupId(groupId);
        List<OmcUserVo> list = uacRpcService.queryOmcUserListByQueryDto(omcUserQueryDto);
        if (list.size() > 0) {
            BeanUtils.copyProperties(list.get(0), omcUserDetailVo);
        }
        if (nursingGroupList.size() > 0) {
            omcUserDetailVo.setNursingGroupName(nursingGroupList.get(0).getName());//填充护工组名称
            omcUserDetailVo.setNursingGroupId(nursingGroupList.get(0).getId());//填充护工组ID
            if (userId.intValue() == nursingGroupList.get(0).getUserId().intValue()) {//是否是班长
                omcUserDetailVo.setMonitor(true);
            }
        }
        return omcUserDetailVo;
    }

    @Override
    public List<Long> isNotNursing(OmcUserQueryDto omcUserQueryDto) {
        omcUserQueryDto.setRoleCode("nursing");  //护工角色编码
        List<Long> userIdList = omcUserQueryDto.getUserIdList();
        List<Long> isNursingList = new ArrayList<>();//储存是护工角色的用户ID
        List<OmcUserVo> list = uacRpcService.queryOmcUserListByQueryDto(omcUserQueryDto);
        if (null != list && list.size() > 0) {
            for (OmcUserVo omcUserVo : list) {
                isNursingList.add(omcUserVo.getUserId());
            }
        }
        userIdList.removeAll(isNursingList);//移除是护工角色的用户ID
        return userIdList;
    }


    /**
     * 护工调换角色时,删除用户绑定的护工 -- 若用户是班长不予删除
     *
     * @param userId
     * @return
     */
    @Override
    public Integer deleteNursingUserBind(Long userId) {
        Long nursingGroupId = selectNuringGroupIdByUserId(userId);
        if (null != nursingGroupId && nursingGroupId > 0) {//如果用户用绑定护工组,才进行解绑
            NursingGroup dto = new NursingGroup();
            dto.setUserId(userId);
            dto.setId(nursingGroupId);
            NursingGroup nursingGroup = selectOne(dto);
            if(null != nursingGroup){//是班长,不予删除绑定关系
                return 0;
            }
            Group group = new Group();
            group.setUserId(userId);
            deleteNursingGroupBind(group);
            return 1;
        }
        return 0;
    }

    @Override
    public OmcUserVo getUserNursingGroupInfo(Long userId) {
        OmcUserVo vo = groupMapper.getUserNursingGroupInfo(userId);
        return vo;
    }


}
